package com.weihua.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

import java.io.IOException;
import java.text.SimpleDateFormat;

public class Jackson {
    private static ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

        mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

        mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);

        mapper.setFilterProvider(new SimpleFilterProvider().setFailOnUnknownId(false));

        mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS); //不转换 NULL属性

        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd hh:mm"));

        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    }

    public static <T> T readValue(String value, Class<T> clazz) {
        try {
            T entity = mapper.readValue(value, clazz);
            return entity;
        } catch (IOException e) {
            String errorMsg = String.format("convert str [%s] to class [%s] error.", value, clazz.getName());
            throw new RuntimeException(e);
        }
    }

    public static JavaType getCollectionType(Class<?> collectionClazz, Class<?>... elementClazz) {
        return mapper.getTypeFactory().constructParametricType(collectionClazz, elementClazz);
    }

    public static String writeValue(Object bean) {
        try {
            String value = mapper.writeValueAsString(bean);
            return value;
        } catch (JsonProcessingException e) {
            String errorMsg = String.format("serial bean [%s] to str error.", bean.toString());
            throw new RuntimeException(e);
        }
    }
}
